package com.project.restaurant.common.exception;

import com.project.restaurant.common.api.ResponseResult;
import com.project.restaurant.common.api.ServiceStateCode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;


@RestControllerAdvice
public class ExceptionTranslator {


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult handleError(Exception e){
        e.printStackTrace();
        return ResponseResult.failure(ServiceStateCode.FAILURE);
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult handleError(ServiceException e){
        e.printStackTrace();
        return ResponseResult.failure(e.getErrorCode());
    }

    /**
     * 缺少必要的请求参数
     * @param e
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult handleError(MissingServletRequestParameterException e) {
        String message = String.format("缺少必要的请求参数: %s", e.getParameterName());
        System.out.println(message);
        return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
    }

    /**
     * 请求参数格式错误
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult handleError(MethodArgumentTypeMismatchException e) {
        String message = String.format("请求参数格式错误: %s", e.getName());
        System.out.println(message);
        return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
    }


    /**
     * 参数验证失败
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult handleError(MethodArgumentNotValidException e) {
        String message = String.format("参数验证失败: %s", e.getMessage());
        System.out.println(message);
        return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
    }
}
